package com.cocola.controller;

import com.cocola.pojo.User;
import com.cocola.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {

    public static String USERNAME;

    @Autowired
    private UserService userService;


    @RequestMapping("/toLogin")
    public String toLogin() {
        System.out.println("loging.........");

        return "login_person";
    }

    /*
    **登陆
     */
    @RequestMapping("/doLogin")
    public String doLogin(String userName, String password, HttpServletRequest request, HttpSession session) {

        System.out.println(userName);
        System.out.println(password);

        if(userService.login(userName, password)) {

            User loginUser = userService.findUser(userName).get(0); //注册的用户是唯一的，所以查询出的List只有一条
            session.setAttribute("loginUser", loginUser);
            USERNAME = loginUser.getUserName();

            return "main";

        }else {
            request.setAttribute("error","用户名或密码错误");
        }
        return "login_person";

    }


    @RequestMapping("/toRegister")
    public String toRegister() {

        return "register";
    }

    /*
    **注册
     */
    @RequestMapping("/doRegister")
    public String register(String userName, String password, String passswordConfirm, String securityQuestion, String securityAnswer, String phone, String securityCode,
                           String email, String userIdcard, String idType, HttpServletRequest request) {

        try {
            if(userService.findUser(userName).isEmpty()) {
                userService.register(userName, password, passswordConfirm, securityQuestion, securityAnswer, phone, securityCode,
                        email, userIdcard, idType);

                return "login_person";
            }else {
                request.setAttribute("error", "该用户已经存在");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "register";
    }



}
